package org.summer.gateway.route;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * nacos动态路由配置
 * @author wjj9132
 * @date 2024/9/29 13:58
 * @since 1.0
 */
@Log4j2
//@Configuration
public class NacosDynamicRoute implements ApplicationRunner {
    private final NacosListener nacosListener;
    private final ConfigService configService;
    private final ObjectMapper objectMapper;
    private static final String ROUTE_DATA_ID = "route-config.json";
    private static final String ROUTE_GROUP = "GVP_TEST_GROUP";
    private static final Integer TIME_OUT = 3000;

//    @Autowired
    public NacosDynamicRoute(NacosConfigProperties nacosConfigProperties, NacosListener nacosListener, ObjectMapper objectMapper) throws NacosException {
        this.nacosListener = nacosListener;
        this.objectMapper = objectMapper;
        Properties properties = new Properties();
        properties.setProperty("serverAddr", nacosConfigProperties.getServerAddr());
        properties.setProperty("namespace", nacosConfigProperties.getNamespace());
        properties.setProperty("username", nacosConfigProperties.getUsername());
        properties.setProperty("password", nacosConfigProperties.getPassword());
        this.configService = NacosFactory.createConfigService(properties);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String routeConfig = this.configService.getConfig(ROUTE_DATA_ID, ROUTE_GROUP, TIME_OUT);
        this.configService.addListener(ROUTE_DATA_ID, ROUTE_GROUP,nacosListener);
        log.info("从nacos配置中读取网关路由json配置: {}",routeConfig);
//        RouteDefinition routeDefinition = objectMapper.readValue(routeConfig, new TypeReference<RouteDefinition>(){});


        List<RouteDefinition> routeDefinitions = objectMapper.readValue(routeConfig, new TypeReference<List<RouteDefinition>>() {});
        routeDefinitions.forEach(routeDefinition -> log.debug("路由信息: {}", routeDefinition));

    }
}
